<?php
namespace app\api\controller\mytool;

use app\api\controller\Base;
use app\api\controller\mytool\Mytool;
use app\api\controller\mytool\Wechat;
use app\api\controller\Pub;
use app\common\model\buss\Buss;
use app\common\model\company\Company;
use app\common\model\company\Contract;
use app\common\model\orderdata\StorageArea;
use app\common\model\orderdata\Storageareachange;
use app\common\model\orderdata\StorageAreaGoods;
use app\common\model\orderdelivery\DeliveryList;
use app\common\model\orderhawa\HawaList;
use app\common\model\orderreceipt\ReceiptList;
use app\common\model\sendmsg\Sendmsg;
use app\common\model\transit\Transitcompany;
use app\common\model\user\User;
use app\common\model\sync\SyncCenter;
use think\Controller;
use app\common\model\approval\Approvallog as ApprovalLog;

class SendMessage extends Base
{
    /**
     * 此文件负责处理通知逻辑
     * @return [type] [description]
     */
    public function index()
    {
        // $sb = self::Orderhawa(1,);
        return 'hello,';
    }

    /**
     * 预约提醒通知模块
     */
    public static function Subscribe($data){
        $today = date('Y-m-d H:i:s',time());
        $rdata['temp']    = WECHATTEMP1;
        $rdata['msgdata'] = array('first' => '您有'.$data['Count'].'条预约信息，请及时处理',
            'keyword1'                        => $today,
            'keyword2'                        => '预约提醒通知',
            'remark'                          => '点击查看预约日程表',
            'url'                             => WEBURL . 'user/schedule_content',
        );
        $rdata['touser']['SendUserId'] = $data['UserId'];
        return self::send($rdata,'subscribe');
    }
    /**
     * 产废订单通知模块
     * @param [type] $type 类型
     * @param [type] $id   [description]
     * @param string $data [description]
     *  1下单待分配
    用户-分配管理者
    用户-用户
    2分配待接单 分配者-制定业务
    3接单通知   业务-用户
    4重量确认通知 业务-用户
    7重量确认通知 用户-业务
    5入库通知   业务-用户
    6订单结算通知 会计-用户
     */
    public static function Orderhawa($type, $id, $data = '')
    {
        if (empty($data)) {
            $data = HawaList::get($id);
        }
        //如果此订单没有绑定用户id 则直接通知企业负责人
        if(empty($data['UpUserId'])){
            $data['company'] = Company::get($data['CompanyId']);
            if(!empty($data['company']['UserId'])){
                $data['UpUserId'] = $data['company']['UserId'];
            }
        }
        $msg = '';
        switch ($type) {
            case 1:
                // 通知分配者
                $data['company'] = Company::get($data['CompanyId']);
                $sb              = self::SOrderhawa(1, $id, $data);
                if (!$sb['code']) {
                    $msg = $msg . '通知分配者' . $sb['msg'];
                }
                //通知产废单位
                $sb = self::SOrderhawa(11, $id, $data);
                if (!$sb['code']) {
                    $msg = $msg . '通知产废单位' . $sb['msg'];
                }
                break;
            case 2:
                $data['company'] = Company::get($data['CompanyId']);
                // 通知收集员
                if (!empty($data['TransitUserId'])) {
                    $data['BussinessId'] = $data['TransitUserId'];
                    $sb                  = self::SOrderhawa(21, $id, $data);
                    if (!$sb['code']) {
                        $msg = $msg . '通知收集员' . $sb['msg'];
                    }
                    break;
                }
                //通知运输公司
                if (!empty($data['TransitCompanyId'])) {
                    $tc                  = Transitcompany::get($data['TransitCompanyId']);
                    $data['BussinessId'] = $tc->UserId;
                    $sb                  = self::SOrderhawa(22, $id, $data);
                    if (!$sb['code']) {
                        $msg = $msg . '通知运输公司' . $sb['msg'];
                    }
                    break;
                }
                //通知业务员
                $sb = self::SOrderhawa(2, $id, $data);
                if (!$sb['code']) {
                    $msg = $msg . '通知业务员' . $sb['msg'];
                }
                break;

            case 3:
                // 通知用户 接单
                if (!empty($data['TransitUserId'])) {
                    $rolename                 = '运输单位收集员';
                    $data['buss']             = User::get($data['TransitUserId']);
                    $data['buss']['UserName'] = $data['buss']['Name'];
                    $data['buss']['UserTel']  = $data['buss']['Iphone'];
                } else {
                    $rolename     = '业务员';
                    $data['buss'] = Buss::get($data['BussinessId']);
                }

                $sb = self::SOrderhawa(3, $id, $data);
                if (!$sb['code']) {
                    $msg = $msg . '通知产废单位' . $sb['msg'];
                }
                break;
            case 4:
                // 通知用户 重量确认
                if (!empty($data['TransitUserId'])) {
                    $data['RoleName']         = '运输单位收集员';
                    $data['buss']             = User::get($data['TransitUserId']);
                    $data['buss']['UserName'] = $data['buss']['Name'];
                    $data['buss']['UserTel']  = $data['buss']['Iphone'];
                } else {
                    $data['RoleName'] = '业务员';
                    $data['buss']     = Buss::get($data['BussinessId']);
                }
                // $data['buss'] = Buss::get($data['BussinessId']);
                $sb           = self::SOrderhawa(4, $id, $data);
                if (!$sb['code']) {
                    $msg = $msg . '通知产废单位' . $sb['msg'];
                }
                break;
            case 41:
                $data['company'] = Company::get($data['CompanyId']);
                //  通知业务员填写订单费用
                $data['RoleName'] = '业务员';
                $data['buss']     = Buss::get($data['BussinessId']);
                $sb           = self::SOrderhawa(41, $id, $data);
                if (!$sb['code']) {
                    $msg = $msg . '通知相关业务人员' . $sb['msg'];
                }
                break;
            case 5:
                // 通知用户 入库通知
                $sb = self::SOrderhawa(5, $id, $data);
                if (!$sb['code']) {
                    $msg = $msg . '通知产废单位' . $sb['msg'];
                }
                break;
            case 51:
                // 通知用户 电子收集单完善后
                $sb = self::SOrderhawa(51, $id, $data);
                if (!$sb['code']) {
                    $msg = $msg . '通知产废单位' . $sb['msg'];
                }
                $sb = self::SOrderhawa(52, $id, $data);
                if (!$sb['code']) {
                    $msg = $msg . '通知业务员' . $sb['msg'];
                }
                break;
            case 6:
                // 通知用户 结算通知
                $sb = self::SOrderhawa(6, $id, $data);
                if (!$sb['code']) {
                    $msg = $msg . '通知产废单位' . $sb['msg'];
                }
                break;
            case 7:
                // 通知收集员 重量确认
                if (!empty($data['TransitUserId'])) {
                    $data['BussinessId'] = $data['TransitUserId'];
                    $sb                  = self::SOrderhawa(7, $id, $data);
                    if (!$sb['code']) {
                        $msg = $msg . '通知运输单位收集员' . $sb['msg'];
                    }
                    break;
                }
                $sb = self::SOrderhawa(7, $id, $data);
                if (!$sb['code']) {
                    $msg = $msg . '通知业务员' . $sb['msg'];
                }
                break;
            default:
                return serr('参数错误');
                break;
        }
        if (empty($msg)) {
            return sok('推送成功');
        } else {
            return serr($msg);
        }
    }

    public static function SOrderhawa($type, $id, $data)
    {
        switch ($type) {
            case 1:
                //通知分配者
                $rdata['temp']    = WECHATTEMP1;
                $rdata['msgdata'] = array('first' => '接到' . $data['company']['Address'] . $data['company']['Name'] . '的产废提单，请尽快分配收集员',
                    'keyword1'                        => $data['UpTime'],
                    'keyword2'                        => '危险废物回收',
                    'remark'                          => '点击查看订单信息',
                    'url'                             => WEBURL . 'manaorder/manaorderhawa?id=' . $id,
                );
                $rdata['touser']['SendPowerCode'] = 204010;
                break;
            case 11:
                //通知产废单位
                $rdata['temp']    = WECHATTEMP1;
                $rdata['msgdata'] = array('first' => '下单成功，我们将尽快为您分配收集员',
                    'keyword1'                        => $data['UpTime'],
                    'keyword2'                        => '危险废物回收',
                    'remark'                          => '点击查看订单信息',
                    'url'                             => WEBURL . 'orderhawa/orderhawa?id=' . $id,
                );
                $rdata['touser']['SendUserId'] = $data['UpUserId'];
                break;
            case 2:
                //通知产废单位
                $rdata['temp']    = WECHATTEMP1;
                $rdata['msgdata'] = array('first' => '接到' . $data['company']['Address'] . $data['company']['Name'] . '的产废提单，请及时处理。',
                    'keyword1'                        => $data['UpTime'],
                    'keyword2'                        => '危险废物回收',
                    'remark'                          => '点击查看订单信息',
                    'url'                             => WEBURL . 'orderhawa/orderhawabuss?id=' . $id,
                );
                $rdata['touser']['SendUserId'] = $data['BussinessId'];
                break;
            case 21:
                //通知运输单位
                $rdata['temp']    = WECHATTEMP1;
                $rdata['msgdata'] = array('first' => '接到' . $data['company']['Address'] . $data['company']['Name'] . '的产废提单，请及时处理。',
                    'keyword1'                        => $data['UpTime'],
                    'keyword2'                        => '危险废物回收',
                    'remark'                          => '点击查看订单信息',
                    'url'                             => WEBURL . 'orderhawa/orderhawatran?id=' . $id,
                );
                $rdata['touser']['SendUserId'] = $data['BussinessId'];
                break;
            case 22:
                //通知运输单位
                $rdata['temp']    = WECHATTEMP1;
                $rdata['msgdata'] = array('first' => '接到' . $data['company']['Address'] . $data['company']['Name'] . '的产废提单，请及时处理。',
                    'keyword1'                        => $data['UpTime'],
                    'keyword2'                        => '危险废物回收',
                    'remark'                          => '点击查看订单信息',
                    'url'                             => WEBURL . 'orderhawa/orderhawatranmana?id=' . $id,
                );
                $rdata['touser']['SendUserId'] = $data['BussinessId'];
                break;
            case 3:
                //通知产废单位
                $rdata['temp']    = WECHATTEMP4;
                $rdata['msgdata'] = array('first' => '我司业务员员已接您提交的产废订单，预计' . $data['ArriveTime'] . '为您上门回收',
                    'keyword1'                        => $data['OrderNumber'],
                    'keyword2'                        => $data['buss']['UserName'],
                    'keyword3'                        => $data['buss']['UserTel'],
                    'keyword4'                        => date('Y-m-d H:i', time()),
                    'remark'                          => '点击查看订单信息',
                    'url'                             => WEBURL . 'orderhawa/orderhawa?id=' . $id,
                );
                $rdata['touser']['SendUserId'] = $data['UpUserId'];
                break;
            case 41:
                //通知业务员
                $rdata['temp']    = WECHATTEMP1.'';
                $rdata['msgdata'] = array('first' => '产废订单费用确认通知',
                    'keyword1'                        => $data['OrderNumber'],
                    'keyword2'                        => '收集人员已修改'.$data['company']['Address'] . $data['company']['Name'] . '订单重量，请及时核算填写相关费用。',
                    'remark'                          => '点击处理订单信息',
                    'url'                             => WEBURL . 'orderhawa/orderhawabuss?id=' . $id,
                );
                $rdata['touser']['SendUserId'] = $data['BussinessId'];
                break;
             case 4:
                //通知产废单位
                $rdata['temp']    = WECHATTEMP1.'';
                $rdata['msgdata'] = array('first' => '产废订单确认通知',
                    'keyword1'                        => $data['OrderNumber'],
                    'keyword2'                        => $data['RoleName'] . '【' . $data['buss']['UserName'] . '】' . '在' . date('Y-m-d H:i', time()) . '为您调整产废订单，请及时确认。',
                    'remark'                          => '点击处理订单信息',
                    'url'                             => WEBURL . 'orderhawa/orderhawa?id=' . $id,
                );
                $rdata['touser']['SendUserId'] = $data['UpUserId'];
                break;
            case 5:
                //通知产废单位
                $rdata['temp']    = WECHATTEMP1.'';
                $rdata['msgdata'] = array('first' => '货物入库提醒',
                    'keyword1'                        => $data['OrderNumber'],
                    'keyword2'                        => '您在' . $data['UpTime'] . '提交的订单已入库,进入页面可查看转移联单。',
                    'remark'                          => '点击查看订单信息',
                    'url'                             => WEBURL . 'orderhawa/orderhawa?id=' . $id,
                );
                $rdata['touser']['SendUserId'] = $data['UpUserId'];
                break;
            case 51:
                //通知产废单位
                $rdata['temp']    = WECHATTEMP1.'';
                $rdata['msgdata'] = array('first' => '电子收集单提醒',
                    'keyword1'                        => $data['OrderNumber'],
                    'keyword2'                        => '您在' . $data['UpTime'] . '提交的订单,已生成电子收集单。',
                    'remark'                          => '点击查看电子收集单',
                    'url'                             => WEBURL . 'print/orderhawa?id=' . $data['OrderPassword'],
                );
                $rdata['touser']['SendUserId'] = $data['UpUserId'];
                break;
            case 52:
                //通知业务员
                $rdata['temp']    = WECHATTEMP1.'';
                $rdata['msgdata'] = array('first' => '电子收集单提醒',
                    'keyword1'                        => $data['OrderNumber'],
                    'keyword2'                        => $data['company']['Address'] . $data['company']['Name'] . '的电子联单批次号已完善，请悉知。',
                    'remark'                          => '点击处理订单信息',
                    'url'                             => WEBURL . 'orderhawa/orderhawabuss?id=' . $id,
                );
                $rdata['touser']['SendUserId'] = $data['BussinessId'];
                break;
            case 6:
                //通知产废单位
                $rdata['temp']    = WECHATTEMP1.'';
                $rdata['msgdata'] = array('first' => '结算完成通知',
                    'keyword1'                        => $data['OrderNumber'],
                    'keyword2'                        => '您在' . $data['UpTime'] . '提交的订单已完成结算。',
                    'remark'                          => '点击查看订单信息',
                    'url'                             => WEBURL . 'orderhawa/orderhawa?id=' . $id,
                );
                $rdata['touser']['SendUserId'] = $data['UpUserId'];
                break;
            case 7:
                //通知产废单位
                $rdata['temp']    = WECHATTEMP1.'';
                $rdata['msgdata'] = array('first' => '订单重量确认通知',
                    'keyword1'                        => $data['OrderNumber'],
                    'keyword2'                        => '产废单位在' . date('Y-m-d H:i', time()) . '确认了您调整的订单重量，运输途中请注意安全。',
                    'remark'                          => '点击处理订单信息',
                    'url'                             => WEBURL . 'orderhawa/orderhawabuss?id=' . $id,
                );
                $rdata['touser']['SendUserId'] = $data['BussinessId'];
                break;
            default:
                # code...
                break;
        }
        return self::send($rdata, 'orderhawa');
    }

    /**
     * 货物入库
     * @param [type] $type [description]
     * @param [type] $id   [description]
     * @param string $data [description]
     * 重量确认通知
    库管-业务
    重量确认 业务-库管
    重量确认 业务-会计
    订单结算通知 会计-业务
     */
    public static function Orderreceipt($type, $id, $data = '')
    {
        if (empty($data)) {
            $data = ReceiptList::get($id);
        }
        $msg = '';
        switch ($type) {
            case 1:
                // 通知运输单位收集员
                if (!empty($data['TransitUserId'])) {
                    $data['BussinessId'] = $data['TransitUserId'];
                    $sb                  = self::SOrderreceipt(11, $id, $data);
                    if (!$sb['code']) {
                        $msg = $msg . '通知收集员' . $sb['msg'];
                    }
                    break;
                }
                //通知业务员
                $sb = self::SOrderreceipt(1, $id, $data);
                if (!$sb['code']) {
                    $msg = $msg . '通知收集员' . $sb['msg'];
                }
                break;
            case 2:
                if (!empty($data['TransitUserId'])) {
                    $user         = User::getpublicinfo($data['TransitUserId']);
                    $data['buss'] = ['UserName' => $user['Name']];
                } else {
                    $data['buss'] = Buss::get($data['BussinessId']);
                }
                $sb = self::SOrderreceipt(2, $id, $data);
                if (!$sb['code']) {
                    $msg = $msg . '通知库管' . $sb['msg'];
                }
                //通知会计结算订单
                $sb = self::SOrderreceipt(21, $id, $data);
                if (!$sb['code']) {
                    $msg = $msg . '通知会计' . $sb['msg'];
                }
                break;
            case 3:
                $sb = self::SOrderreceipt(3, $id, $data);
                if (!$sb['code']) {
                    $msg = $msg . '通知收集员' . $sb['msg'];
                }
            // no break
            default:
                return serr('参数错误');
                break;
        }
        if (empty($msg)) {
            return sok('推送成功');
        } else {
            return serr($msg);
        }
    }

    public static function SOrderreceipt($type, $id, $data)
    {
        switch ($type) {
            case 1:
                $rdata['temp']    = WECHATTEMP1.'';
                $rdata['msgdata'] = array('first' => '入库确认',
                    'keyword1'                        => $data['OrderNumber'],
                    'keyword2'                        => '库管已进行货物盘点，请检查重量是否正确并且核实需要入库的订单（核实后无法修改）。',
                    'remark'                          => '点击查看订单信息',
                    'url'                             => WEBURL . 'orderreceipt/orderreceiptbuss?id=' . $id,
                );
                $rdata['touser']['SendUserId'] = $data['BussinessId'];
                break;
            case 11:
                $rdata['temp']    = WECHATTEMP1.'';
                $rdata['msgdata'] = array('first' => '入库确认',
                    'keyword1'                        => $data['OrderNumber'],
                    'keyword2'                        => '库管已进行货物盘点，请检查重量是否正确并且核实入库的订单（核实后无法修改）。',
                    'remark'                          => '点击查看订单信息',
                    'url'                             => WEBURL . 'orderreceipt/orderreceipttran?id=' . $id,
                );
                $rdata['touser']['SendUserId'] = $data['BussinessId'];
                break;
            case 2:
                $rdata['temp']    = WECHATTEMP1.'';
                $rdata['msgdata'] = array('first' => '入库通知',
                    'keyword1'                        => $data['OrderNumber'],
                    'keyword2'                        => $data['buss']['UserName'] . '的货物入库成功',
                    'remark'                          => '点击查看订单信息',
                    'url'                             => WEBURL . 'orderreceipt/orderreceipt?id=' . $id,
                );
                $rdata['touser']['SendUserId'] = $data['WarehouseId'];
                break;
            case 21:
                $rdata['temp']    = WECHATTEMP1.'';
                $rdata['msgdata'] = array('first' => '入库通知',
                    'keyword1'                        => $data['OrderNumber'],
                    'keyword2'                        => $data['buss']['UserName'] . '的货物入库成功',
                    'remark'                          => '点击查看订单信息',
                    'url'                             => WEBURL . 'orderreceipt/orderreceiptacco?id=' . $id,
                );
                $rdata['touser']['SendPowerCode'] = 203001;
                break;
            case 3:
                $rdata['temp']    = WECHATTEMP1.'';
                $rdata['msgdata'] = array('first' => '费用通知',
                    'keyword1'                        => $data['OrderNumber'],
                    'keyword2'                        => '订单费用已结算',
                    'remark'                          => '点击查看订单信息',
                    'url'                             => WEBURL . 'orderreceipt/orderreceiptbuss?id=' . $id,
                );
                $rdata['touser']['SendUserId'] = $data['BussinessId'];
                break;

            default:
                # code...
                break;
        }
        return self::send($rdata, 'orderreceipt');
    }

    /**
     * 货物出库
     * @param [type] $type [description]
     * @param [type] $id   [description]
     * @param string $data [description]
     *  提单待配货通知 会计-库管
    装货出库通知 库管-会计
     */
    public static function Orderdelivery($type, $id, $data = '')
    {
        if (empty($data)) {
            $data = DeliveryList::get($id);
        }
        $msg = '';
        switch ($type) {
            case 1:
                $sb = self::SOrderdelivery(1, $id, $data);
                if (!$sb['code']) {
                    $msg = $msg . '通知库管' . $sb['msg'];
                }
                break;
            case 2:
                $sb = self::SOrderdelivery(2, $id, $data);
                if (!$sb['code']) {
                    $msg = $msg . '通知会计' . $sb['msg'];
                }
                break;
            default:
                return serr('参数错误');
                break;
        }
        if (empty($msg)) {
            return sok('推送成功');
        } else {
            return serr($msg);
        }
    }

    public static function SOrderdelivery($type, $id, $data)
    {
        switch ($type) {
            case 1:
                $rdata['temp']    = WECHATTEMP1.'';
                $rdata['msgdata'] = array('first' => '出库通知',
                    'keyword1'                        => date('Y-m-d H:i:s',time()),
                    'keyword2'                        => '收到新的出库单，请您及时配货准备出库',
                    'remark'                          => '点击查看订单信息',
                    'url'                             => WEBURL . 'orderdelivery/orderdeliveryware?id=' . $id,
                );
                $rdata['touser']['SendPowerCode'] = 202002;
                break;
            case 2:
                $rdata['temp']    = WECHATTEMP1.'';
                $rdata['msgdata'] = array('first' => '出库通知',
                    'keyword1'                        => date('Y-m-d H:i:s',time()),
                    'keyword2'                        => $data['UpTime'] . '提交的出库单，货物已出库。请及时处理',
                    'remark'                          => '点击查看订单信息',
                    'url'                             => WEBURL . 'orderdelivery/orderdeliveryacco?id=' . $id,
                );
                $rdata['touser']['SendUserId'] = $data['UpUserId'];
                break;

            default:
                # code...
                break;
        }
        return self::send($rdata, 'orderdelivery');
    }

    /**
     * 货物出库
     * @param [type] $type [description]
     * @param [type] $id   [description]
     * @param string $data [description]
     *  提单待配货通知 会计-库管
    装货出库通知 库管-会计
     */
    public static function Contract($type, $id, $data = '')
    {
        if (empty($data)) {
            $data = Contract::get($id);
        }
        $data['buss'] = User::get($data['BussinessId']);
        $data['company'] = Company::get($data['CompanyId']);
        $msg             = '';
        switch ($type) {
            case 1:
                $sb = self::SContract(1, $id, $data);
                if (!$sb['code']) {
                    $msg = $msg . '通知用户' . $sb['msg'];
                }
                break;
            case 2:
                $sb           = self::SContract(2, $id, $data);
                if (!$sb['code']) {
                    $msg = $msg . '通知收集员' . $sb['msg'];
                }
                $sb = self::SContract(21, $id, $data);
                if (!$sb['code']) {
                    $msg = $msg . '通知会计' . $sb['msg'];
                }
                break;
            case 3:
                $sb = self::SContract(3, $id, $data);
                if (!$sb['code']) {
                    $msg = $msg . '通知用户' . $sb['msg'];
                }
                break;
            case 4:
                $sb           = self::SContract(4, $id, $data);
                if (!$sb['code']) {
                    $msg = $msg . '通知用户' . $sb['msg'];
                }
                break;
            case 5:
                $sb           = self::SContract(5, $id, $data);
                if (!$sb['code']) {
                    $msg = $msg . '通知财务' . $sb['msg'];
                }
                break;    

            default:
                return serr('参数错误');
                break;
        }
        if (empty($msg)) {
            return sok('推送成功');
        } else {
            return serr($msg);
        }
    }

    public static function SContract($type, $id, $data)
    {
        //没有用户id 的话直接通知会计确认
        if (($type == 1||$type == 4) && empty($data['company']['UserId'])) {
            $type = 21;
        }
        switch ($type) {
            case 1:
                $rdata['temp']    = WECHATTEMP1;
                $rdata['msgdata'] = array('first' => '合同通知',
                    'keyword1'                        => $data['CreateTime'],
                    'keyword2'                        => '您有一份待确认的合同，请您及时处理。',
                    'remark'                          => '点击查看合同信息',
                    'url'                             => WEBURL . 'contract/contracthawa?id=' . $id,
                );
                $rdata['touser']['SendUserId'] = $data['company']['UserId'];
                break;
            case 2:
                $rdata['temp']    = WECHATTEMP1;
                $rdata['msgdata'] = array('first' => '合同通知',
                    'keyword1'                        => $data['CreateTime'],
                    'keyword2'                        => '产废单位' . $data['company']['Name'] . '已确认您提交的合同。',
                    'remark'                          => '点击查看合同信息',
                    'url'                             => WEBURL . 'contract/contractbuss?id=' . $id,
                );
                $rdata['touser']['SendUserId'] = $data['BussinessId'];
                break;
            case 21:
                $rdata['temp']    = WECHATTEMP1;
                $rdata['msgdata'] = array('first' => '新合同通知',
                    'keyword1'                        => $data['CreateTime'],
                    'keyword2'                        => '业务员' . $data['buss']['Name'] . '为产废单位' . $data['company']['Name'] . '创建了新的合同。',
                    'remark'                          => '点击查看合同信息',
                    'url'                             => WEBURL . 'contract/contractacco?id=' . $id,
                );
                $rdata['touser']['SendPowerCode'] = 203003;

                break;
            case 3:
                $rdata['temp']    = WECHATTEMP1;
                $rdata['msgdata'] = array('first' => '费用通知',
                    'keyword1'                        => $data['SettlementTime'],
                    'keyword2'                        => '您与我司签订的合同费用已结算。',
                    'remark'                          => '点击查看合同信息',
                    'url'                             => WEBURL . 'contract/contracthawa?id=' . $id,
                );
                $rdata['touser']['SendUserId'] = $data['company']['UserId'];
                break;
            case 4:
                $rdata['temp']    = WECHATTEMP1;
                $rdata['msgdata'] = array('first' => '修改通知',
                    'keyword1'                        => $data['CreateTime'],
                    'keyword2'                        => '我司' . $data['buss']['Name'] . '为您修改合同信息，请您及时处理',
                    'remark'                          => '点击查看合同信息',
                    'url'                             => WEBURL . 'contract/contracthawa?id=' . $id,
                );
                $rdata['touser']['SendUserId'] = $data['company']['UserId'];
                break;
            case 5:
                $rdata['temp']    = WECHATTEMP1;
                $rdata['msgdata'] = array('first' => '支付通知',
                    'keyword1'                        => date('Y-m-d H:i:s',time()),
                    'keyword2'                        => '由【'.$data['buss']['Name'].'】负责【'.$data['company']['Name'].'】的危废合同进入扫码支付流程,付款金额为：'.$data['ContractCost'].'元。',
                    'remark'                          => '点击查看合同信息',
                    'url'                             => WEBURL . 'contract/contractacco?id=' . $id,
                );
                $rdata['touser']['SendPowerCode'] = 203011;
                break;
            case 6:
                $rdata['temp']    = WECHATTEMP1;
                $rdata['msgdata'] = array('first' => '逾期提醒',
                    'keyword1'                        => '逾期提醒',
                    'keyword2'                        => '今天您有'.$data['Count'].'份合同临期。',
                    'remark'                          => '点击查看逾期合同列表',
                    'url'                             => WEBURL . 'public/list?type=contract_deadline_buss',
                );
                $rdata['touser']['SendUserId'] = $data['BussinessId'];
                break;
            default:
                # code...
                break;
        }
        return self::send($rdata, 'contract');
    }
    /**
     * 货物出库
     * @param [type] $type [description]
     * @param [type] $id   [description]
     * @param string $data [description]
     *  提单待配货通知 会计-库管
    装货出库通知 库管-会计
     */
    public static function Quotation($type, $data = '')
    {
        $msg = '';
        switch ($type) {
            case 1:
                $sb = self::SQuotation(1, $data);
                if (!$sb['code']) {
                    $msg = $msg . '通知用户' . $sb['msg'];
                }
                break;
            case 2:
                $sb = self::SQuotation(2, $data);
                if (!$sb['code']) {
                    $msg = $msg . '通知收集员' . $sb['msg'];
                }
                break;
            default:
                return serr('参数错误');
                break;
        }
        if (empty($msg)) {
            return sok('推送成功');
        } else {
            return serr($msg);
        }
    }

    public static function SQuotation($type, $data)
    {
        switch ($type) {
            case 1:
                $rdata['temp']    = WECHATTEMP1;
                $rdata['msgdata'] = array('first' => '报价通知',
                    'keyword1'                        => $data['StartTime'],
                    'keyword2'                        => '我司已更新报价',
                    'remark'                          => '注：实际价格以入库时间的最新报价为准，点击即可查看目前报价。',
                    'url'                             => WEBURL . 'quot/index?type=hawa',
                );
                $rdata['touser']['SendPowerCode'] = 101004;
                $rdata['SendTime']                = $data['StartTime'];
                break;
            case 2:
                $rdata['temp']    = WECHATTEMP1;
                $rdata['msgdata'] = array('first' => '报价通知',
                    'keyword1'                        => $data['StartTime'],
                    'keyword2'                        => '我司已更新报价',
                    'remark'                          => '注：实际价格以入库时间的最新报价为准，点击即可查看目前报价。',
                    'url'                             => WEBURL . 'quot/index?type=buss',
                );
                $rdata['touser']['SendPowerCode'] = 201005;
                $rdata['SendTime']                = $data['StartTime'];
                break;
            default:
                # code...
                break;
        }
        return self::send($rdata, 'quotation');
    }

    /**
     * 同步中心指令
     * @param  [type] $type [description]
     * @param  [type] $id   [description]
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public static function Sync($type,$id,$data)
    {
        switch ($type) {
            // 待审核
            case 1:
                $rdata['temp']    = WECHATTEMP1;
                $rdata['msgdata'] = array(
                    'first'    => '审核通知',
                    'keyword1' => date('Y-m-d H:i:s',time()),
                    'keyword2' => $data['Type'],
                    'remark'   => '查看详情',
                    'url'      => WEBURL . 'sync/codeinfo?id='.$id,
                );
                $rdata['touser']['SendPowerCode'] = 206001;
                break;
            case 2:
                // 同步成功
                $rdata['temp']    = WECHATTEMP1;
                $witecount = SyncCenter::where('Status',SyncCenter::STATESTART)->count();
                $str = empty($witecount)?'全部执行完毕':'还有'.$witecount.'个指令在执行中';
                $rdata['msgdata'] = array(
                    'first'    => '同步指令操作成功,目前'.$str.'。',
                    'keyword1' => date('Y-m-d H:i:s',time()),
                    'keyword2' => $data['Type'],
                    'remark'   => '查看详情',
                    'url'      => WEBURL . 'sync/codeinfo?id='.$id,
                );
                $rdata['touser']['SendUserId'] = $data['UpUserId'];
                break;
            case 3:
                $msg = json_array($data['SynMsg'],true);
                if(!empty($msg['msg'])){
                    $msg = $msg['msg'];
                }
                // 出现问题需要处理
                $rdata['temp']    = WECHATTEMP1;
                $rdata['msgdata'] = array(
                    'first'    => '同步指令出现了问题：'.$msg,
                    'keyword1' => date('Y-m-d H:i:s',time()),
                    'keyword2' => $data['Type'],
                    'remark'   => '请及时处理',
                    'url'      => WEBURL . 'sync/codeinfo?id='.$id,
                );
                $rdata['touser']['SendUserId'] = $data['UpUserId'];
                break;
            case 4:
                // 取消成功
                $rdata['temp']    = WECHATTEMP1;
                $rdata['msgdata'] = array(
                    'first'    => '同步指令已取消',
                    'keyword1' => date('Y-m-d H:i:s',time()),
                    'keyword2' => $data['Type'],
                    'remark'   => '查看详情',
                    'url'      => WEBURL . 'sync/codeinfo?id='.$id,
                );
                $rdata['touser']['SendUserId'] = $data['UpUserId'];
                break;
            default:
               
               break;
        }
        return self::send($rdata, 'sync');
    }
    
    /**
     * 库存微调指令
     * @param  [type] $type [description]
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public static function reviewadjust($type, $id, $data = [])
    {

        if (empty($data) || empty($data['StorageAreaId'])) {
            $data = Storageareachange::get($id);
        }
        $areagood = StorageAreaGoods::get($data['StorageAreaGoodsId']);
        $area = StorageArea::get($areagood['StorageAreaId']);

        if ($data['Weight'] > 0) {
            $data['Weight'] = '增加' . $data['Weight'] . 'kg';
        } else {
            $data['Weight'] = '减少' . (0 - $data['Weight']) . 'kg';
        }
        switch ($type) {
            // 申请微调
            case 1:
                $rdata['temp']    = WECHATTEMP1;
                $rdata['msgdata'] = array(
                    'first'    => '微调申请',
                    'keyword1' => date('Y-m-d H:i:s', time()),
                    'keyword2' => $area['GroupName'] . $area['Name'] . $areagood['GoodName'] .  '调整：' . $data['Weight'],
                    'remark'   => '点击即可查看，请及时处理',
                    'url'      => WEBURL . 'ware/fine_tuningt_select?id=' . $area['StorageAreaId'],
                );
                $rdata['touser']['SendPowerCode'] = 203009;
                break;
            case 2:
                // 微调通过 - 给库管
                $rdata['temp']    = WECHATTEMP1;
                $rdata['msgdata'] = array(
                    'first'    => '微调通知',
                    'keyword1' => date('Y-m-d H:i:s', time()),
                    'keyword2' => $area['GroupName'] . $area['Name'] . $areagood['GoodName'] .  '调整：' . $data['Weight'],
                    'remark'   => '点击即可查看详情',
                    'url'      => WEBURL . 'ware/fine_tuningt_details?id=' . $area['StorageAreaId'],
                );
                $rdata['touser']['SendUserId'] = $data['UpUserId'];
                break;
            case 21:
                // 微调通过 - 给股东
                $rdata['temp']    = WECHATTEMP1;
                $rdata['msgdata'] = array(
                    'first'    => '微调通知',
                    'keyword1' => date('Y-m-d H:i:s', time()),
                    'keyword2' => $area['GroupName'] . $area['Name'] . $areagood['GoodName'] .  '调整：' . $data['Weight'],
                    'remark'   => '点击即可查看详情',
                    'url'      => WEBURL . 'ware/fine_tuningt_select?id=' . $area['StorageAreaId'],
                );
                $rdata['touser']['SendPowerCode'] = 204009;
                break;
            case 3:
                // 微调通过
                $rdata['temp']    = WECHATTEMP1;
                $rdata['msgdata'] = array(
                    'first'    => '拒绝通知',
                    'keyword1' => date('Y-m-d H:i:s', time()),
                    'keyword2' => $area['GroupName'] . $area['Name'] . $areagood['GoodName'] .  '调整：' . $data['Weight'],
                    'remark'   => '点击即可查看详情',
                    'url'      => WEBURL . 'ware/fine_tuningt_details?id=' . $area['StorageAreaId'],
                );
                $rdata['touser']['SendUserId'] = $data['UpUserId'];
                break;

        }
        return self::send($rdata, 'reviewadjust');
    }

    /**
     * 审批指令
     * @param  [type] $type     [description]
     * @param  [type] $id       [description]
     * @param  array  $data     [description]
     * @param  array  $touserid [需要通知的用户列表]
     * @return [type]           [description]
     */
    public static function approval($type, $data = [],$touserid=[])
    {
        $typetext = ApprovalLog::getTypeText($data['Type']);
        switch ($type) {
            // 系统直接通知审批
            case 1:
                $createuserinfo = User::get($data['CreateUserId']);
                $rdata['temp']    = WECHATTEMP1;
                $rdata['msgdata'] = array(
                    'first'    => '审批申请',
                    'keyword1' => $data['CreateTime'],
                    'keyword2' => $createuserinfo['Name'] .'的订单，需要您进行'.$typetext ,
                    'remark'   => '请及时处理',
                    'url'      => WEBURL . 'approval/approval?type=' . $data['Type'].'&id='.$data['CorrelationId'],
                );
                $rdata['touser']['SendUserId'] = $touserid;
                break;
            case 2:
                // 被驳回后通知创建者
                $rdata['temp']    = WECHATTEMP1;
                $rdata['msgdata'] = array(
                    'first'    => '审批被驳回',
                    'keyword1' => $data['CreateTime'],
                    'keyword2' => '您的'.$typetext .'被驳回',
                    'remark'   => '点击即可查看详情',
                    'url'      => WEBURL . 'approval/approval?type=' . $data['Type'].'&id='.$data['CorrelationId'],
                );
                $rdata['touser']['SendUserId'] = $data['CreateUserId'];
                break;
            case 3:
                // 审批通过
                $rdata['temp']    = WECHATTEMP1;
                $rdata['msgdata'] = array(
                    'first'    => '审批已通过',
                    'keyword1' => $data['CreateTime'],
                    'keyword2' => '您的'.$typetext .'已通过',
                    'remark'   => '点击即可查看详情',
                    'url'      => WEBURL . 'approval/approval?type=' . $data['Type'].'&id='.$data['CorrelationId'],
                );
                $rdata['touser']['SendUserId'] = $data['CreateUserId'];
                break;
            case 4:
                $createuserinfo = User::get(Pub::userid());
                $rdata['temp']    = WECHATTEMP1;
                $rdata['msgdata'] = array(
                    'first'    => '审批提醒',
                    'keyword1' => $data['CreateTime'],
                    'keyword2' => $createuserinfo['Name'] .'提醒您进行'.$typetext ,
                    'remark'   => '请及时处理',
                    'url'      => WEBURL . 'approval/approval?type=' . $data['Type'].'&id='.$data['CorrelationId'],
                );
                $rdata['touser']['SendUserId'] = $touserid;
                break;

        }
        return self::send($rdata, 'approval');
    }


    public function test(){
                $rdata['temp']    = WECHATTEMP1;
                $rdata['msgdata'] = array('first' => '11111',
                    'keyword1'                        => '2023-10-15 16:27:47',
                    'keyword2'                        => '我司已更新报价',
                    'remark'                          => '注：实际价格以入库时间的最新报价为准，点击即可查看目前报价。',
                    'url'                             => WEBURL . 'quot/index?type=buss',
                );
                $rdata['touser']['SendRole'] = 203;
        return self::send($rdata, 'quotation');
    }
    /**
     * 微信模板消息提醒规格化
     * @return [type] [description]
     */
    public static function wechat_massage_formate($data){
        $sb = get_config_value('new_wechat_message_state');
        if(empty($sb)){
            //老版本直接通过
        }else{
            //新版本调整
            switch ($data['temp']) {
                case WECHATTEMP1:
                    $newfiled =['first'=>'short_thing7','keyword1'=>'time1','keyword2'=>'thing10','remark'=>'thing11'];
                    break;
                case WECHATTEMP4:
                    $newfiled =['first'=>'short_thing7','keyword1'=>'character_string9','keyword2'=>'thing2','keyword4'=>'time1','remark'=>'thing10'];
                    $data['msgdata']['keyword2'] = $data['msgdata']['keyword2'].$data['msgdata']['keyword3'];
                    unset($data['keyword3']);
                    break;
                case WECHATTEMP1.'':
                    $newfiled =['first'=>'thing6','keyword1'=>'character_string4','keyword2'=>'phrase8','remark'=>'thing3','keyword3'=>'time9'];
                    break;
                default:
                    return myerr('模板消息发送失败');
                    break;
            }
            //字符串名字修改
            foreach ($newfiled as $key => $value) {
                if(empty($data['msgdata'][$key])){
                    $data['msgdata'][$key] = '';
                }
                $ndata[$value] = $data['msgdata'][$key];
            }
            if(!empty($data['msgdata']['url'])){
                $ndata['url'] =$data['msgdata']['url'];
            }
            foreach ($ndata as $key => $value) {
                // $skey=preg_replace("/d+/",'', $key);
                $skey=preg_replace("/\\d+/",'', $key);
                switch ($skey) {
                    case 'short_thing':
                        //短事物,5个以内字符，不支持换行
                        $ndata[$key] = mb_substr($value,0,5);
                        break;
                    case 'thing':
                        // 20个字符以内
                        $ndata[$key] = mb_substr($value,0,20);
                        break;
                    case 'character_string':
                        // 32位以内数字、字母或符号
                        $ndata[$key] = mb_substr($value,0,32);
                        break;
                    case 'phrase':
                        // 汉字，5个以内汉字
                        preg_match_all('/[\x{4e00}-\x{9fff}]+/u', $value, $value);
                        $value = implode('',$value[0]);
                        $ndata[$key] = mb_substr($value,0,5);
                        break;
                    case 'time':
                        // 汉字，5个以内汉字
                        if(empty($value)||strripos($value,'-')==false||strripos($value,'年')==false||strripos($value,':')==false){
                            $ndata[$key] = date('Y-m-d H:i:s',time());
                        }
                        break;
                }
            }
            $data['msgdata']=$ndata;
        }
        return $data;
    }
    /**
     * 发送通知消息
     * @param  [type]  $rdata    [description]
     * @param  [type]  $type     [description]
     * @param  boolean $is_robat [description]
     * @return [type]            [description]
     */
    public static function send($rdata, $type, $is_robat = false)
    {   
        //兼容最新微信通知
        $rdata = self::wechat_massage_formate($rdata);
        $nrdata = $rdata;
        if (!empty($rdata['touser']['SendUserId'])) {
            if (!is_array($rdata['touser']['SendUserId'])) {
                $nrdata['touser'] = [$rdata['touser']['SendUserId']];
            } else {
                $nrdata['touser'] = $rdata['touser']['SendUserId'];
            }
        }

        if (!empty($rdata['touser']['SendRole'])) {
            $nrdata['touser'] = User::role_getuserid($rdata['touser']['SendRole']);
        }

        if (!empty($rdata['touser']['SendPowerCode'])) {
            $nrdata['touser'] = User::powercode_getuserid($rdata['touser']['SendPowerCode']);
        }

        if (empty($rdata['touser'])) {
            return serr('缺少用户id');
        }
        //去重
        $nrdata['touser'] = array_unique($nrdata['touser']);
        //将userid 转变为wechatopenid
        $nrdata['touser'] = User::getWechatIdlist($nrdata['touser']);
        //二次去重
        $nrdata['touser'] = array_unique($nrdata['touser']);

        if (empty($nrdata['touser'][0])) {
            return serr('缺少用户openid');
        }
        $ndata  = new Sendmsg;
        $sbpush = true; //判断是否已经推送过
        if (empty($rdata['SendTime']) || (strtotime($rdata['SendTime']) <= time())) {
            $sbpush = false;
            $sb     = Wechat::SendMessage($nrdata);
            if (!$sb['code']) {
                if ($is_robat) {
                    return serr($sb['msg']['msg']);
                } else {
                    //推送失败后将在5分钟后再次尝试推送
                    $ndata->ErrorLog   = date('Y-m-d H:i', time()) . ':' . $sb['msg']['msg'];
                    $ndata->SendCount  = 1;
                    $rdata['SendTime'] = date('Y-m-d H:i', time() + 300);
                }
            } else {
                //成功后直接返回
                return $sb;
            }
        }
        //将数据放到推送表中
        $ndata->Content  = json_encode($rdata);
        $ndata->MsgType  = $type;
        $ndata->SendTime = $rdata['SendTime'];
        if (!empty($rdata['touser']['SendUserId'])) {
            $ndata->SendUserId = $rdata['touser']['SendUserId'];
        }

        if (!empty($rdata['touser']['SendRole'])) {
            $ndata->SendRole = $rdata['touser']['SendRole'];
        }

        if (!empty($rdata['touser']['SendPowerCode'])) {
            $ndata->SendPowerCode = $rdata['touser']['SendPowerCode'];
        }
        $ndata->SendType     = 'wechat';
        $ndata->CreateUserId = Pub::userid();
        $ndata->CreateTime   = date('Y-m-d H:i', time());
        $ndata->save();
        if ($sbpush) {
            return sok('创建成功,将在' . $rdata['SendTime'] . '发出通知。');
        } else {
            return serr('推送失败，将在5分钟后尝试再次通知。');
        }
    }
}
